package com.im.gate.codec;


import com.im.gate.MesRequest;
import com.rou.im.framework.core.Request;
import com.rou.im.framework.core.request.RequestHeader;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * <p>
 *
 *   packet---序列化---request
 *
 *
 *
 * </p>
 *
 * @author GaoShuangWen
 * @since 2020-04-06 14:49
 */

public class MessageDecoder extends ByteToMessageDecoder  {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

     /*   CharSequence sessionId = byteBuf.readCharSequence(
                Constants.SESSION_ID_LENGTH, Charset.defaultCharset());	// 读取sessionId
        message.setSessionId((String)sessionId);*/

        // 标记一下当前的readIndex的位置
        in.markReaderIndex();
        // 判断包头长度
        if (in.readableBytes() < 18) {// 不够包头
            return;
        }
        RequestHeader header=new RequestHeader();
        in.readShort();
        //header.setMagicNumber(in.readShort());
        header.setClientVersion(in.readInt());
        header.setCmdId(in.readInt());
        header.setSeq(in.readInt());
        // 读取传送过来的消息的长度。
        int bodyLength = in.readInt();
        header.setBodyLength(bodyLength);
        // 长度如果小于0
        if (bodyLength < 0) {// 非法数据，关闭连接
            ctx.close();
        }
        if (bodyLength > in.readableBytes()) {
            // 重置读取位置
            in.resetReaderIndex();
            return;
        }
        byte[] array;
        if (in.hasArray()) {
            //堆缓冲
            ByteBuf slice = in.slice();
            array = slice.array();
        } else {
            //直接缓冲
            array = new byte[bodyLength];
            in.readBytes(array, 0, bodyLength);
        }

        Request request = new MesRequest(header,array);
        out.add(request);
    }


}
